/*
 * @Description: 获取二维码的常州实例
 * @Author: yingying.fan
 * @Date: 2019-03-27 10:17:57
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-03-29 20:33:56
 */
<script>
// import { getUserId } from '@/utils/UserBeanUtils.js'
import { getUserInfo } from 'vue-xiaobu-utils'
import { getWalletAmount } from '../../api/api.js'
export default {
  data() {
    return {
      codeIndex: 0,
      // 下面这部分是常州用的数据
      cacheCardInfo: null,
      BUS_CARD_INFO_KEY: 'faekf3lb3lfab113d',
      maxOfflineQrcode: 10 // 连续进行离线请码的最大次数
    }
  },
  computed: {
    // 提示充值的余额限制，单位分
    rechargeLimit() {
      return this.$store.getters.rechargeLimit
    },
    // 不出码的余额限制，单位分
    qrcodeBalanceLimit() {
      return this.$store.getters.qrcodeBalanceLimit
    }
  },
  mounted() {
    // this.userId = getUserInfo().USER_ID
    // this.userId = getUserId()
    // this.cacheCardInfo = this.getCardInfoFromCache()
  },
  destroyed() {

  },
  methods: {
    // 通过余额判断获取
    async getQrcodeByAmount(amount = 0) {
      // if (this.isFirstPayBank || this.getQrCodeFuncError) {
      if (this.isFirstPayBank) {
        // this.getAmountResult = 0
        // 代表可请码
        this.isQrImgDisable = false
        return this.getQrcodeToShow()
      } else {
        // 如果第一个可用的支付方式不是银行卡的话就需要判断余额限制
        if (this.amount !== null) {
          console.log('未获取余额')
          // return this.judgeAmount(this.amount)
          return this.judgeAmount(this.amount)
        } else {
          let amount
          try {
            amount = await getWalletAmount()
            // TODO: 每次获取余额都修改store中的记录
            this.$store.dispatch('fetchAmount', amount)
            if (!this.isFirstPayBank) {
              // 如果支付方式不是银行卡，记得更新支付方式的余额展示
              this.$store.dispatch('fetchPayDesc', '&nbsp;(' + amount.toFixed(2) + '元)')
            }
            console.log('获取余额成功了')
            this.getAmountResult = 1
            return await this.judgeAmount(amount)
          } catch (error) {
            // TODO:请求余额失败则判断本地缓存中的余额离线请码
            // 虽然获取钱包余额失败了，但是可以通过点击重新获取二维码
            if (this.getAmountResult === 0) {
              this.getAmountResult = 2
            }
            this.isQrImgDisable = false
            console.log('获取余额失败了', error.message)
            throw error
          }
        }
      }
    },
    judgeAmount(amount) {
      // 使用过一次的余额要置为null
      console.log('在判断余额', amount)
      this.amount = null
      let needContinue = true
      return new Promise((resolve, reject) => {
        if (amount < this.qrcodeBalanceLimit) {
          this.limitHint = '余额低于' + this.qrcodeBalanceLimit + '元，请充值'
          if (!this.hasBindBankCard) {
            // 当用户未绑定银行卡时，低于限制的额度就不出码，也不继续请码协议；绑定银行卡了则无影响
            this.qrcodeSrc = this.disableQrImg
            this.isQrImgDisable = true
            needContinue = false
            console.log('不用出码啦！')
            // 因为是条件判断不可以展示二维码所以不需要通知
            // reject(new Error('no qrcode'))
          }
        } else if (amount < this.rechargeLimit) {
          this.limitHint = '余额低于' + this.rechargeLimit + '元，请充值'
        } else {
          this.limitHint = ''
        }
        if (needContinue) {
          this.isQrImgDisable = false
          this.getQrcodeToShow().then(() => {
            resolve('')
          }).catch(error => {
            // console.log(111, error)
            reject(error)
          })
        }
      })
    },
    // 请求到二维码后的结果处理,成功则展示图,失败则toast提示错误
    async getQrcodeToShow() {
      console.log('准备要请求二维码了')
      let qrcode
      try {
        qrcode = await this.getQrCodeJudgeCache()
        this.getQrCodeFuncError = false
        // this.qrcodeSrc = qrcode
        this.setQrcodeToImage(qrcode)
        console.log('结果图：', qrcode)
      } catch (error) {
        this.getQrCodeFuncError = true
        this.$toastMsg(error.message)
      }
      // return this.getQrCodeJudgeCache().then(qrcode => {
      //   this.qrcodeSrc = qrcode
      //   console.log('结果图：', qrcode)
      //   return ''
      // }).catch(error => {
      //   this.$toastMsg(error.message)
      //   throw error
      // })
    },
    // 缓存中存在卡信息时通过离线请码，否则通过在线请码
    getQrCodeJudgeCache() {
      // if (this.cacheCardInfo) {
      //   return this.getQrcodeWhenOffline()
      // } else {
      // TODO:目前由于余额限制必须通过在线请码
      return this.getQrcodeWhenOnline()
      // }
    },
    /**
     * 离线请求二维码
     * @param {Number} offlineGetCodeCount 当前离线请码次数
     */
    async getQrcodeWhenOffline(offlineGetCodeCount) {
      console.log('离线请码中')
      if (offlineGetCodeCount >= this.maxOfflineQrcode) {
        // TODO: 请求次数超出离线最大请求次数
        throw new Error('您的网络比较差,请确保网络良好后重试')
      }
      let code = await this.getQrcodeBySdk()
      // 更新离线请码次数+1
      this.addOfflineQrcodeCount()
      return code
      // return new Promise((resolve, reject) => {
      //   if (offlineGetCodeCount >= this.maxOfflineQrcode) {
      //     // TODO: 请求次数超出离线最大请求次数
      //     reject(new Error('您的网络比较差,请确保网络良好后重试'))
      //   } else {
      //     this.getQrcodeBySdk().then(code => {
      //       // 更新离线请码次数+1
      //       this.addOfflineQrcodeCount()
      //       resolve(code)
      //     }).catch(error => {
      //       reject(error)
      //     })
      //   }
      // })
    },
    // 在线请求二维码
    getQrcodeWhenOnline() {
      console.log('在线请码中')
      return this.getQrcodeBySdk()
    },
    // 通过sdk请求二维码
    getQrcodeBySdk() {
      console.log('sdk请码中')
      return new Promise((resolve, reject) => {
        if (window.x_thirdparty && window.x_thirdparty.riseRidingCode) {
          window.x_thirdparty.riseRidingCode(
            msg => {
              // 成功回调
              console.log('离线请码成功：' + msg)
              let msgObj = JSON.parse(msg)
              let code = msgObj.RIDING_CODE
              if (code.indexOf('data:image/png;base64') < 0) {
                code = 'data:image/png;base64,' + code
              }
              resolve(code)
            },
            error => {
              // 失败回调
              console.log('离线请码失败：' + error)
              let errObj = JSON.parse(error)
              reject(new Error(errObj.ERRMSG))
            },
            // this.userId
            getUserInfo().USER_ID
          )
        } else {
          // TODO:插件失败处理
          // return getQrcodeBySdk(userId)
          if (!this.codeIndex) {
            reject(new Error('二维码请求失败，请重试'))
            this.codeIndex++
          }
          resolve(
            'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553613235806&di=d12a5d2eecf27f75c8c018ed39677bf8&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201207%2F05%2F20120705102047_EthKT.jpeg'
          )
        }
      })
    }
    // getCardInfoFromCache() {
    //   let info = window.localStorage.getItem(this.BUS_CARD_INFO_KEY)
    //   if (info) {
    //     return JSON.parse(info)
    //   } else {
    //     return null
    //   }
    // },
    // setCardInfoToCache(count, cardNo, showCardNo, owner, amount) {
    //   this.cacheCardInfo = {
    //     COUNT: count,
    //     CARD_NO: cardNo,
    //     SHOW_CARD_NO: showCardNo,
    //     OWNER: owner,
    //     AMOUNT: amount
    //   }
    //   window.localStorage.setItem(this.BUS_CARD_INFO_KEY, JSON.stringify(this.cacheCardInfo))
    // },
    // addOfflineQrcodeCount() {
    //   let count = this.cacheCardInfo.COUNT + 1
    //   this.cacheCardInfo.COUNT = count
    //   window.localStorage.setItem(this.BUS_CARD_INFO_KEY, JSON.stringify(this.cacheCardInfo))
    // }
  }
}
</script>
